package com.treasure.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.treasure.common.model.PageResult;
import com.treasure.common.model.SessionUser;
import com.treasure.common.model.SessionUserHolder;
import com.treasure.common.types.Corp;
import com.treasure.common.types.Question;
import com.treasure.domain.domain.RelatedTextExtractionDomainService;
import com.treasure.domain.domain.entity.SegmentDocEntity;
import com.treasure.infrastructure.model.po.*;
import com.treasure.infrastructure.repository.dao.mapper.AiRobotMapper;
import com.treasure.infrastructure.repository.dao.mapper.ChatHistoryDetailMapper;
import com.treasure.infrastructure.repository.dao.mapper.ChatHistoryMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.treasure.infrastructure.repository.dao.mapper.CorpUserInfoMapper;
import com.treasure.web.command.PageConvertor;
import com.treasure.web.command.request.chat.ChatHistoryDetailRequest;
import com.treasure.web.command.request.chat.ChatHistoryRequest;
import com.treasure.web.command.request.chat.ChatRelationRequest;
import com.treasure.web.command.request.chat.CorpChatHistoryDetailRequest;
import com.treasure.web.command.response.ConversationListResponse;
import com.treasure.web.command.response.CorpChatHistoryDetailResponse;
import com.treasure.web.command.response.chat.ChatHistoryDetailResponse;
import com.treasure.web.command.response.chat.ChatHistoryResponse;
import com.treasure.web.command.response.chat.ChatRelationResponse;
import com.treasure.web.mapstruct.ChatHistoryAssembler;
import com.treasure.web.mapstruct.SegmentDocAssembler;
import com.treasure.web.service.IChatHistoryService;
import com.treasure.web.service.IConversationDetailsService;
import com.treasure.web.service.ICorpInfoService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sunhongmin
 * @since 2023-08-31
 */
@Service
@RequiredArgsConstructor
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements IChatHistoryService {

    private final ChatHistoryMapper chatHistoryMapper;
    private final ChatHistoryDetailMapper chatHistoryDetailMapper;
    private final RelatedTextExtractionDomainService relatedTextExtractionDomainService;
    private final CorpUserInfoMapper corpUserInfoMapper;
    private final IConversationDetailsService conversationDetailsService;
    private final AiRobotMapper robotMapper;
    private final ICorpInfoService corpInfoService;

    @Override
    public IPage<ChatHistoryResponse> getChatHistoryList(SessionUser sessionUser, ChatHistoryRequest chatHistoryRequest) {

        QueryWrapper<ChatHistory> chatHistoryQueryWrapper = new QueryWrapper<>();
        chatHistoryQueryWrapper.eq("corp_id", sessionUser.getCorpId())
                .eq("user_id", sessionUser.getUserId())
                .orderBy(true, false, "create_time");

        PageHelper.startPage(chatHistoryRequest.getPage(), chatHistoryRequest.getPageSize());
        List<ChatHistory> chatHistories = chatHistoryMapper.selectList(chatHistoryQueryWrapper);
        PageInfo<ChatHistory> pageInfo = new PageInfo<>(chatHistories);

        List<ChatHistoryResponse> chatHistoryResponses = ChatHistoryAssembler.INSTANCE.convertToChatHistoryResponseList(chatHistories);
        IPage<ChatHistoryResponse> resultPage = new Page<>();
        resultPage.setPages(pageInfo.getPages());
        resultPage.setRecords(chatHistoryResponses);
        resultPage.setTotal(pageInfo.getTotal());
        resultPage.setSize(pageInfo.getSize());
        resultPage.setCurrent(pageInfo.getPageNum());
        return resultPage;
    }

    @Override
    public ChatHistoryDetailResponse getChatHistoryDetailList(Corp corp, ChatHistoryDetailRequest chatRecordRequest) {
        chatRecordRequest.valiadate();
        SessionUser sessionUser = SessionUserHolder.getAndCheckSessionUser();
        // 分页查询
        QueryWrapper<ChatHistoryDetail> chatHistoryDetailQueryWrapper = new QueryWrapper<>();
        chatHistoryDetailQueryWrapper.eq("corp_id", corp.getValue())
                .eq("user_id", sessionUser.getUserId())
                .eq("interaction_id", chatRecordRequest.getInteractionId())
                .orderByAsc("id");
        ;

        PageHelper.startPage(chatRecordRequest.getPage(), chatRecordRequest.getPageSize());
        List<ChatHistoryDetail> chatHistoryDetailList = chatHistoryDetailMapper.selectList(chatHistoryDetailQueryWrapper);
        PageInfo<ChatHistoryDetail> chatHistoryDetailPageInfo = new PageInfo<>(chatHistoryDetailList);
        // 结果转换
        ChatHistoryDetailResponse chatHistoryDetailResponse = new ChatHistoryDetailResponse();
        chatHistoryDetailResponse.setInteractionId(chatRecordRequest.getInteractionId());
        IPage<ChatHistoryDetailResponse.HistoryResponse> resultPage = new Page<>();
        resultPage.setPages(chatHistoryDetailPageInfo.getPages());
        resultPage.setTotal(chatHistoryDetailPageInfo.getTotal());
        resultPage.setSize(chatHistoryDetailPageInfo.getSize());
        resultPage.setCurrent(chatHistoryDetailPageInfo.getPageNum());
        List<ChatHistoryDetailResponse.HistoryResponse> historyResponses = ChatHistoryAssembler.INSTANCE.convertToChatHistoryDetailList(chatHistoryDetailList);
        resultPage.setRecords(historyResponses);
        chatHistoryDetailResponse.setChatHistoryListPage(resultPage);
        return chatHistoryDetailResponse;
    }

    @Override
    public List<ChatRelationResponse> getQuestionRelationDocLit(ChatRelationRequest chatRelationRequest) {
        List<SegmentDocEntity> segmentDocEntities = relatedTextExtractionDomainService.relatedTextExtraction(new Question(chatRelationRequest.getQuestion()));
        return SegmentDocAssembler.INSTANCE.convertChatRelationResponseList(segmentDocEntities);
    }

    @Override
    public PageResult<ConversationListResponse> queryChatHistoryDetailList(CorpChatHistoryDetailRequest corpChatHistoryDetailRequest, String corpId) {
        QueryWrapper<ConversationDetails> conversationDetailsQuery = new QueryWrapper<>();
        conversationDetailsQuery.lambda()
                .orderByDesc(ConversationDetails::getCreateTime);
        if (StringUtils.isNotBlank(corpId)) {
            conversationDetailsQuery.lambda()
                    .eq(ConversationDetails::getCorpId, corpId);
        }
        if (StringUtils.isNotBlank(corpChatHistoryDetailRequest.getTimeStart())) {
            conversationDetailsQuery.lambda()
                    .gt(ConversationDetails::getCreateTime, corpChatHistoryDetailRequest.getTimeStart());
        }
        if (StringUtils.isNotBlank(corpChatHistoryDetailRequest.getTimeEnd())) {
            conversationDetailsQuery.lambda()
                    .lt(ConversationDetails::getCreateTime, corpChatHistoryDetailRequest.getTimeEnd());
        }
        // userName 查询
        if (StringUtils.isNotBlank(corpChatHistoryDetailRequest.getUserName())) {
            List<CorpUserInfo> corpUserInfoList = corpInfoService.queryUserListByNameLike(corpChatHistoryDetailRequest.getUserName(), corpId);
            if (CollectionUtils.isEmpty(corpUserInfoList)) {
                return PageConvertor.emptyPage();
            }
            List<String> userIdList = corpUserInfoList.stream().map(CorpUserInfo::getUserId).collect(Collectors.toList());
            conversationDetailsQuery.lambda().in(ConversationDetails::getUserId, userIdList);
        }

        PageHelper.startPage(corpChatHistoryDetailRequest.getPage(), corpChatHistoryDetailRequest.getPageSize());
        List<ConversationDetails> chatHistoryDetailList = conversationDetailsService.list(conversationDetailsQuery);
        PageInfo<ConversationDetails> chatHistoryDetailPageInfo = new PageInfo<>(chatHistoryDetailList);

        List<ConversationDetails> pageInfoList = chatHistoryDetailPageInfo.getList();
        if (CollectionUtils.isEmpty(pageInfoList)) {
            return PageConvertor.emptyPage();
        }

        List<ConversationListResponse> response = convertResponse(corpId, pageInfoList);
        return PageConvertor.convertPage(chatHistoryDetailPageInfo, response);
    }

    @NotNull
    private List<ConversationListResponse> convertResponse(String corpId, List<ConversationDetails> pageInfoList) {
        List<String> userIdList = pageInfoList.stream().map(ConversationDetails::getUserId).collect(Collectors.toList());
        QueryWrapper<CorpUserInfo> userIdInQuery = new QueryWrapper<>();
        userIdInQuery.lambda()
                .in(CorpUserInfo::getUserId, userIdList);

        if (StringUtils.isNotBlank(corpId)) {
            userIdInQuery.lambda()
                    .eq(CorpUserInfo::getCorpId, corpId);
        }

        List<CorpUserInfo> corpUserInfoList = corpUserInfoMapper.selectList(userIdInQuery);
        Map<String, String> userIdMap = corpUserInfoList.stream().collect(Collectors.toMap(CorpUserInfo::getUserId, CorpUserInfo::getUsername));

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        List<ConversationListResponse> response = new ArrayList<>(pageInfoList.size());
        for (ConversationDetails conversationDetails : pageInfoList) {
            ConversationListResponse corpChatHistoryDetailResponse = new ConversationListResponse();
            corpChatHistoryDetailResponse.setId(conversationDetails.getId());
            corpChatHistoryDetailResponse.setCorpId(conversationDetails.getCorpId());
            if (Objects.nonNull(conversationDetails.getRobotId()) && !Objects.equals(conversationDetails.getRobotId(), -1)) {
                QueryWrapper<AiRobot> robotQuery = new QueryWrapper<>();
                robotQuery.lambda()
                        .eq(AiRobot::getId, conversationDetails.getRobotId());
                AiRobot aiRobot = robotMapper.selectOne(robotQuery);
                if (Objects.nonNull(aiRobot)) {
                    corpChatHistoryDetailResponse.setRobotName(aiRobot.getRobotName());
                }
            }
            corpChatHistoryDetailResponse.setUserName(userIdMap.get(conversationDetails.getUserId()));
            corpChatHistoryDetailResponse.setCreated(formatter.format(conversationDetails.getCreateTime()));
            corpChatHistoryDetailResponse.setQuestion(conversationDetails.getQuestion());
            corpChatHistoryDetailResponse.setAnswer(conversationDetails.getAnswer());
            corpChatHistoryDetailResponse.setInputTokens(conversationDetails.getInputTokens());
            corpChatHistoryDetailResponse.setOutputTokens(conversationDetails.getOutputTokens());
            response.add(corpChatHistoryDetailResponse);
        }
        return response;
    }


}
